﻿using System.Timers;
using System.IO;

namespace DotNet.Common
{
    public class FileWatcher
    {
        FileSystemWatcher m_watcher;
        Timer m_timer;
        string m_filePath;

        public event StringInvoker FileChanged;

        public string FilePath
        {
            set
            {
                m_watcher.Path = Path.GetDirectoryName(value);
                m_watcher.Filter = Path.GetFileName(value);
                m_filePath = value;
            }
        }

        public FileWatcher()
        {
            m_watcher = new FileSystemWatcher();
            m_watcher.NotifyFilter = NotifyFilters.LastWrite;
            m_watcher.Changed += new FileSystemEventHandler(watcher_Changed);
            m_watcher.EnableRaisingEvents = false;

            m_timer = new Timer(500);
            m_timer.AutoReset = false;
            m_timer.Enabled = false;
            m_timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
        }

        public FileWatcher(string filepath)
            : this()
        {
            this.FilePath = filepath;
        }

        public void Start()
        {
            m_watcher.EnableRaisingEvents = true;
        }

        public void Stop()
        {
            m_watcher.EnableRaisingEvents = false;
        }

        private void watcher_Changed(object sender, FileSystemEventArgs e)
        {
            if (!m_timer.Enabled)
            {
                m_timer.Enabled = true;
            }
        }

        void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            m_timer.Enabled = false;

            if (FileChanged != null)
            {
                m_watcher.EnableRaisingEvents = false;
                {
                    FileChanged(m_filePath);
                }
                m_watcher.EnableRaisingEvents = true;
            }
        }
    }
}
